package com.peking.donations.util;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * Created by YGR on 16/2/19.
 */
public class HttpClientUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtils.class);

    /**
     * post请求
     * 
     * @param url
     * @param formParams
     * @return
     */
    public static String doPost(RestTemplate restTemplate, String url, Map<String, String> formParams) {
        if (MapUtils.isEmpty(formParams)) {
            return doPost(restTemplate, url);
        }

        try {
            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
            //formParams.keySet().stream().forEach(key -> requestEntity.add(key, MapUtils.getString(formParams, key, "")));
            for(String key : formParams.keySet()){
                requestEntity.add(key,MapUtils.getString(formParams, key, ""));
            }

            return restTemplate.postForObject(url, requestEntity, String.class);
        } catch (Exception e) {
            LOGGER.error("POST请求出错：{}", url, e);
        }

        return null;
    }

    /**
     * post请求
     * 
     * @param url
     * @return
     */
    public static String doPost(RestTemplate restTemplate, String url) {
        try {
            return restTemplate.postForObject(url, HttpEntity.EMPTY, String.class);
        } catch (Exception e) {
            LOGGER.error("POST请求出错：{}", url, e);
        }

        return null;
    }

    /**
     * get请求
     * 
     * @param url
     * @return
     */
    public static String doGet(RestTemplate restTemplate, String url) {
        try {
            return restTemplate.getForObject(url, String.class);
        } catch (Exception e) {
            LOGGER.error("GET请求出错：{}", url, e);
        }

        return null;
    }
}
